import { Component, Emit, Prop, Watch } from 'vue-facing-decorator'
import Render from '@/render/Render'
import toNative from '@/utils/toNative'
import renderModal, {
    getModelValue,
    initModelValue,
    type FormModalDto
} from '@/components/modal/Modal'
import { addInsureIndustry, editInsureIndustry } from '@/api/insureIndustry'
import type { AddType } from '@/api/types'
import type { InsureIndustryListDto } from '@/api/insureIndustry/types'
@Component
export class AddIndustryPop extends Render {
    @Prop({ default: false }) show!: boolean
    @Prop() addType!: AddType
    @Prop() curData?: InsureIndustryListDto

    @Emit('update:show')
    showChange(val: boolean) {
        return val
    }

    @Emit('refresh')
    handleRefresh() {}

    @Watch('show', { immediate: true })
    async handleWatchShow() {
        this.formConfig.show = this.show
        if (this.show && this.addType === 'edit') {
            initModelValue(this.formConfig, this.curData)
        }
        this.formConfig.title = this.addType === 'edit' ? '编辑行业' : '新增行业'
    }

    formConfig = this.initFormConfig() as FormModalDto

    initFormConfig() {
        return {
            title: '添加行业',
            width: '450px',
            theme: 'dark',
            show: false,
            params: {
                confirmText: '确定'
            },
            items: {
                name: {
                    name: '行业名称',
                    element: 'input'
                }
            },
            complete: async () => {
                const data = getModelValue(this.formConfig)
                if (this.addType === 'add') {
                    await addInsureIndustry(data)
                } else {
                    data.id = this.curData?.id
                    await editInsureIndustry(data)
                }
                this.handleRefresh()
                this.handleClose()
            },
            cancel: () => {
                this.handleClose()
            }
        } as FormModalDto
    }

    handleClose() {
        this.formConfig.show = false
        this.showChange(false)
        initModelValue(this.formConfig, {})
    }

    render() {
        return <>{renderModal(this.formConfig)}</>
    }
}

export default toNative<
    { addType: AddType; curData: InsureIndustryListDto },
    { refresh: () => void }
        >(AddIndustryPop)
